<!--
- Author:  LiShibin.
- Date:    2017/7/4 0004.
- File:    index.
-->
<template>
  <div>
    <div class="Topmenu"><i @click="$utils.back" class="iconfont icon-youjiantou"><a href=""></a></i>
      <h1>购物车</h1>
      <span></span>
    </div>
    <div class="Web_Box" :class="{'no-margin-bottom':editing}">
      <!--店铺商品Start ShoppingCartPage-->
      <div class="">
        <div class="f-oh" style="margin-top:50px;">
          <div v-show="goodsList.data.length > 0" class="gouwuche">
            <!--<p class="gouwucheshangpu"><i class="iconfont icon-weixuanzhong1"></i>taozhi非自营</p>-->
            <ul>
              <li v-for="item in goodsList.data">
                <mt-cell-swipe style="background: none"
                  :right="[{content: '删除',style: { background: 'red', color: '#fff', width: '60px', 'text-align': 'center'  },handler: () => {delGoodsFromCart(item)}}]">
                <i @click="switchSelect(item)"
                   :class="{'icon-weixuanzhong1': selectedCartIdList.indexOf(item.cart_id) === -1, 'icon-xuanzhong1':  selectedCartIdList.indexOf(item.cart_id) !== -1}"
                   class="iconfont fl lh4rem" style="margin-right: 0rem"></i>
                <div @click="gotoGoodsDetail(item.goods_commonid)" class="gouwucheimg">
                  <!--<img :src="$config.website + $config.goodsImgSrc + item.goods_image" alt="">-->
                  <img :src="item.goods_image" alt="">
                </div>
                <div style="padding: 0;width: 100%" class="gouwucheright">
                  <p @click="gotoGoodsDetail(item.goods_commonid)" class="gouwucherightname" style="width: 8rem">{{item.goods_name}}</p>
                  <span class="gouwuchenewold">9.5新未使用</span>
                  <p style="left: 0;width: 100%" class="gouwuchejiage">￥{{item.goods_price | discount(item.groupbuy_rebate)}}
                    <!--<span style="color: #333;margin-left: 5px;">x </span>-->
                    <span style="float: right;margin-right: 5px">
                      <span><i class="iconfont icon-jianhao" @click="reduceNum(item)" style="margin-left: 10px;color: #2f2f2f;"></i>
                      <span style="color: #2f2f2f;padding: 2px 25px;background: #f6f6f6;">{{item.goods_num}}</span>
                      <i class="iconfont icon-jiahao" @click="addNum(item)" style="color: #2f2f2f;"></i></span>
                    </span>
                  </p>
                </div>
                </mt-cell-swipe>
                <!--<i class="iconfont icon-guanbi" style="margin-top: -8px;margin-right: 8px;height: auto"></i>-->
              </li>
            </ul>
          </div>
        </div>
        <!--<div class="ShopGoods EditPro hidden bor_b_dcdddd mb10">-->
          <!--<div class="ProList">-->
            <!--<ul>-->
              <!--<li v-for="item in goodsList.data">-->
                <!--<div class="Choice" @click="switchSelect(item)" v-show="!editing">-->
                  <!--<i class="iconfont icon-weixuanzhong1" v-if="selectedCartIdList.indexOf(item.cart_id) === -1"></i>-->
                  <!--<i class="iconfont icon-xuanzhong1" v-else></i>-->
                <!--</div>-->
                <!--<div class="Pic">-->
                  <!--<img :src="$config.website + $config.goodsImgSrc + item.goods_image" alt=""/></div>-->
                <!--<div class="Con" style="width: 10.5rem;">-->
                  <!--<div class="pl20 f-cb">-->
                    <!--<span class="detete" @click="delGoodsFromCart(item)"><i class="iconfont icon-del3" style="padding:0 5px"></i></span>-->
                    <!--<h2 class="" style="width: 80%; margin: 0 !important;">-->
                      <!--<span @click="gotoGoodsDetail(item.goods_commonid)">{{item.goods_name}}</span></h2>-->
                  <!--</div>-->
                  <!--<div class="cr_898989 pl20" v-show="(item.erp_storage && item.erp_storage <= 0) || item.goods_state != '1'">-->
                    <!--<i class="iconfont icon-shixiao"></i>-->
                  <!--</div>-->
                  <!--<div class="pl20">-->
                    <!--<p class="Attribute" v-show="item.goods_spec.length > 0">-->
                      <!--<span v-for="attr in item.goods_spec">{{attr.name}} </span></p>-->
                    <!--<div class="PriceQuantity f-cb" v-show="item.erp_storage > 0">-->
                      <!--<span class="fl cr_ea5413">￥{{item.goods_price | discount(item.groupbuy_rebate)}}</span>-->
                      <!--<div class="Edit">-->
                        <!--<i class="iconfont icon-jian1" :class="{'jian1-active': parseInt(item.goods_num) > parseInt(item.goods_add_num || 1)}" @click="reduceNum(item)"></i>-->
                        <!--<input type="tel" class="num" @blur="handleNumChange(item)" v-model="item.goods_num" style="height: 1rem;border: none;display: inline-block;vertical-align: middle;width: 2.5rem;font-size: 0.8rem;color: #000;border-radius: 2px;text-align: center;">-->
                        <!--<i class="iconfont icon-jia1" :class="{'jian1-active': parseInt(item.goods_num) + parseInt(item.goods_add_num || 1) <= parseInt(item.erp_storage)}" @click="addNum(item)" style="color: #898989"></i>-->
                      <!--</div>-->
                    <!--</div>-->
                  <!--</div>-->
                <!--</div>-->
              <!--</li>-->
            <!--</ul>-->
          <!--</div>-->
        <!--</div>-->
      </div>
      <!--店铺商品End-->
    </div>
    <div class="gouwuchenav">
      <span class="gouwuchenavleft">
        <i class="iconfont icon-xuanzhong1 mr20" @click="switchSelectAll(false)" v-if="selectedCartIdList.length > 0 && selectedCartIdList.length === goodsList.data.length"></i>
        <i class="iconfont icon-weixuanzhong1 mr20" @click="switchSelectAll(true)" v-else></i>全选
      </span>
      <!--<span @click="delCartList" :class="{'confirm-unactive': totalNum <= 0}" class="gouwuchebtn" style="">删除({{selectedCartIdList.length}})</span>-->
      <span @click="gotoOrderConfirm" :class="{'confirm-unactive': totalNum <= 0}" class="gouwuchebtn">结算({{selectedCartIdList.length}})</span>
      <span class="gouwucheheji"> 合计￥{{totalPrice}}</span>
    </div>
    <!--<div class="ShopGoodsOperation BottomGd" v-show="!editing">-->
      <!--<div class="left fl">-->
        <!--<i class="iconfont icon-select" @click="switchSelectAll(false)" v-if="selectedCartIdList.length > 0 && selectedCartIdList.length === goodsList.data.length"></i>-->
        <!--<i class="iconfont icon-pitch2" @click="switchSelectAll(true)" v-else></i>-->
        <!--<span class="text">全选</span>-->
        <!--<div class="Statistics fr tr">-->
          <!--<p class="Total">合计：<span class="cr_ea5413">￥{{totalPrice}}</span></p>-->
          <!--<p class="Freight" style="background-color: transparent">不含运费</p>-->
        <!--</div>-->
      <!--</div>-->
      <!--<div class="right fr">-->
        <!--<button type="button" class="but" :class="{'confirm-unactive': totalNum <= 0}" @click="gotoOrderConfirm">结算({{totalNum}})</button>-->
      <!--</div>-->
    <!--</div>-->
    <!--<empty-data :show="goodsList.requested && goodsList.data.length <= 0"></empty-data>-->
    <div class="Cart_nodata" v-show="goodsList.requested && goodsList.data.length <= 0">
      <i class="iconfont icon-kong"></i>
      <p>购物车还是空的哦</p>
      <a style="background-color: #e3c143;" href="javascript:void(0)" @click="gotoHome">去逛逛</a>
    </div>
    <!--<back-nav></back-nav>-->
  </div>
</template>

<script>
  import {MessageBox, CellSwipe} from 'mint-ui'
  //  import {mapModules, mapRules} from 'vuet'

  export default{
//    mixins: [
//      mapModules({selectedCartIdList: 'selectedCartIdList'}),
//      mapRules({need: 'selectedCartIdList'})
//    ],
    data() {
      return {
        goodsList: {requested: false, data: []},
        editing: false, // 是否正在编辑
        selectedCartIdList: []
      }
    },
    computed: {
      totalPrice: function () {
        let total = 0
        for (let i = 0; i < this.selectedCartIdList.length; i++) {
          for (let j = 0; j < this.goodsList.data.length; j++) {
            if (this.goodsList.data[j].cart_id === this.selectedCartIdList[i]) {
              if (!this.goodsList.data[j].goods_num || this.goodsList.data[j].goods_num == '') {
                total += 0
              } else {
                total += parseFloat(this.goodsList.data[j].goods_price) * parseFloat(this.goodsList.data[j].groupbuy_rebate / 100) * parseInt(this.goodsList.data[j].goods_num)
              }
              continue
            }
          }
        }
        return total.toFixed(2)
      },
      totalNum: function () {
        let total = 0
        for (let i = 0; i < this.selectedCartIdList.length; i++) {
          for (let j = 0; j < this.goodsList.data.length; j++) {
            if (this.goodsList.data[j].cart_id === this.selectedCartIdList[i]) {
              total += parseInt(this.goodsList.data[j].goods_num)
              continue
            }
          }
        }
        return total
      }
    },
    components: {
      'mt-cell-swipe': CellSwipe
    },
    created() {
      this.getGoodsListInCart()
    },
    methods: {
      delCartList() {
        let cartIdListStr = this.selectedCartIdList.join(',')
        console.log(cartIdListStr)
      },
      gotoHome() {
        this.$router.push({name: 'home'})
      },
      gotoGoodsDetail(goodsCommonid) {
        this.$router.push({name: 'goods-detail', params: {id: goodsCommonid}})
      },
      gotoOrderConfirm() {
        if (this.selectedCartIdList.length <= 0) {
          this.$toast('请先选择要结算的商品')
          return
        }
        let cartIdListStr = this.selectedCartIdList.join(',')
        this.$router.push({name: 'order-confirm', query: {cart: cartIdListStr}})
      },
      switchEditing(boolValue) {
        this.editing = boolValue
      },
      findGoodsInGoodsList(cartId) {
        for (let i = 0; i < this.goodsList.data.length; i++) {
          if (this.goodsList.data[i].cart_id === cartId) {
            return {goods: this.goodsList.data[i], index: i}
          }
        }
        return {goods: null, index: -1}
      },
      switchSelect(goods) {
        let index = this.selectedCartIdList.indexOf(goods.cart_id)
        if (index !== -1) { // 已选
          this.selectedCartIdList.splice(index, 1)
        } else { // 未选
          this.selectedCartIdList.push(goods.cart_id)
        }
      },
      switchSelectAll(boolValue) {
        if (!boolValue) { // 全不选
          this.selectedCartIdList = []
        } else { // 全选
          let tmpArray = []
          for (let i = 0; i < this.goodsList.data.length; i++) {
            tmpArray.push(this.goodsList.data[i].cart_id)
          }
          this.selectedCartIdList = tmpArray
        }
      },
      handleNumChange(goods) {
        if (!goods.erp_storage) {
          this.$toast('尚未获取到该商品的库存')
          return
        }
        let packNum = parseInt(goods.goods_add_num || 1)
        console.log('blur..')
        if (goods.goods_num == '' || goods.goods_num == 0) {
          goods.goods_num = packNum
          return
        }
        let mul = parseInt(parseInt(goods.goods_num) / packNum) // 倍数
        let remain = parseInt(goods.goods_num) % packNum // 余数
        if (remain != 0) {
          goods.goods_num = packNum * (mul + 1)
        }
        if (parseInt(goods.goods_num) + packNum >= parseInt(goods.erp_storage)) {
          this.$toast('超过商品库存数量了~')
          return
        }
        this.$request.modifyGoodsNumToBuy(goods.cart_id, parseInt(goods.goods_num)).then(() => {
        }).catch(e => {
          this.$toast('修改购买数量失败:' + e.msg)
        })
      },
      addNum(goods) {
        let packNum = parseInt(goods.goods_add_num || 1)
        if (!goods.goods_storage) {
          this.$toast('尚未获取到该商品的库存')
          return
        }
        if (parseInt(goods.goods_num) + packNum >= parseInt(goods.goods_storage)) {
          this.$toast('超过商品库存数量了~')
          return
        }
        this.$request.modifyGoodsNumToBuy(goods.cart_id, parseInt(goods.goods_num) + packNum).then(() => {
          let goodsEdit = this.findGoodsInGoodsList(goods.cart_id).goods
          goodsEdit.goods_num = parseInt(goodsEdit.goods_num)
          goodsEdit.goods_num += packNum
        }).catch(e => {
          this.$toast('修改购买数量失败:' + e.msg)
        })
      },
      reduceNum(goods) {
        let packNum = parseInt(goods.goods_add_num || 1)
        if (parseInt(goods.goods_num) <= packNum) {
          return
        }
        this.$request.modifyGoodsNumToBuy(goods.cart_id, goods.goods_num - packNum).then(() => {
          let goodsEdit = this.findGoodsInGoodsList(goods.cart_id).goods
          goodsEdit.goods_num = parseInt(goodsEdit.goods_num)
          goodsEdit.goods_num -= packNum
        }).catch(e => {
          this.$toast('修改购买数量失败' + e.msg)
        })
      },
      getGoodsListInCart() {
        this.$request.getGoodsListInCart().then(data => {
          this.goodsList.data = data
          for (let i = 0; i < data.length; i++) {
            this.$request.getErpStorage(data[i].goods_serial).then(erp_storage => {
              this.$set(this.goodsList.data[i], 'erp_storage', erp_storage)
            }).catch(e => {
              this.$set(this.goodsList.data[i], 'erp_storage', '0')
              console.error('获取ERP库存失败', e)
            })
          }
        }).catch(e => {
          console.error(e)
          this.$toast('获取购物车列表失败:' + e.msg)
        }).finally(() => {
          this.goodsList.requested = true
        })
      },
      delGoodsFromCart(goods) {
        MessageBox.confirm(`你确定要删除该商品吗?`).then(action => {
          this.$request.delGoodsFromCart(goods.cart_id).then(data => {
            let index = this.findGoodsInGoodsList(goods.cart_id).index
            this.goodsList.data.splice(index, 1)
            let index2 = this.selectedCartIdList.indexOf(goods.cart_id)
            if (index2 != -1) {
              this.selectedCartIdList.splice(index2, 1)
            }
            this.$toast('删除成功')
          }).catch(e => {
            this.$toast('删除购物车失败:' + e.msg)
          })
        }).catch(() => {
        })
      }
    }
  }
</script>

<style>
  .no-margin-bottom {
    margin-bottom: 0;
  }

  .jian1-active {
    color: #45a73a !important;
  }

  .confirm-unactive {
    background-color: #dddddd !important;
  }
  .gouwuche{margin: 10px auto;padding: 0rem 0 !important;}
  .gouwuche .icon-xuanzhong1, .gouwuche .icon-weixuanzhong1{padding-left: 0.6rem;padding-right: 0.5rem;margin: 0;flex-shrink: 0;}
  .gouwuche ul li{display: flex;margin: 0 !important;}
  .gouwuche>ul>li:not(:last-of-type){border-bottom: 5px solid #f7f7f7;}
  .gouwucheimg{flex-shrink: 0;}
  .mint-cell-value{
    padding: 0.5rem 0;
  }
</style>
